

import UIKit
import Kingfisher

extension UIImageView {
    
    func setImage(url: String?, placeholder: UIImage? = nil, fade: Bool = true, completion: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) {
        
        guard let urlString = url, let URL = URL(string: urlString) else {
            image = placeholder
            completion?(.failure(.requestError(reason: .emptyRequest)))
            return
        }
        
        var options: KingfisherOptionsInfo? = nil
        if fade {
            options = [
                .transition(.fade(0.2)), // 默认淡入动画
                .cacheOriginalImage      // 缓存原始图片
            ]
        }
        self.kf.setImage(with: URL, placeholder: placeholder, options: options, completionHandler: completion)
    }
    
}


extension UIImageView {
    /// 获取 imageView 当前 image 的显示区域（frame）
    func imageContentFrame() -> CGRect {
        guard let image = self.image else { return .zero }
        guard image.size.width > 0 && image.size.height > 0 else { return .zero }

        let viewSize = self.bounds.size
        let imageSize = image.size

        let scaleX = viewSize.width / imageSize.width
        let scaleY = viewSize.height / imageSize.height
        let scale = min(scaleX, scaleY)

        let width = imageSize.width * scale
        let height = imageSize.height * scale

        let x = (viewSize.width - width) / 2.0
        let y = (viewSize.height - height) / 2.0

        return CGRect(x: x, y: y, width: width, height: height)
    }
}
